package cn.tedu.store.product.webapi.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Api(tags = "本地图片存储路径生成")
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Value("${picture.dirPath}")
    private String dirPath;

    @ApiOperation("删除图片")
    @PostMapping("/remove")
    public void remove(String url){
        new File(dirPath+url).delete();
    }

    @ApiOperation("生成路径")
    @PostMapping("")
    public String upload(MultipartFile pic) throws IOException {
        //获取唯一文件名
        String fileName = pic.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;
        //准备文件夹
        File dirFile = new File(dirPath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //准备文件完整路径
        String filePath = dirPath + "/" + fileName;
        pic.transferTo(new File(filePath));
        return "/"+fileName;
    }

}
